package com.nunbey.lingxi.service;


import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.db.nosql.redis.RedisDS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nunbey.lingxi.config.lincat.spring.mail.MailBean;
import com.nunbey.lingxi.config.lincat.spring.mail.MailUtil;
import com.nunbey.lingxi.dao.UserAccountMapper;
import com.nunbey.lingxi.dao.UserInfoMapper;
import com.nunbey.lingxi.mode.useraccount.UserAccountEntity;
import com.nunbey.lingxi.mode.useraccount.UserLoginVO;
import com.nunbey.lingxi.mode.useraccount.UserSignDTO;
import com.nunbey.lingxi.mode.userinfo.UserInfoEntity;
import common.webresult.WebResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.params.SetParams;
import util.AESUtil;


/**
 * @author lincat
 */
@Service
public class UserAccountService {
    @Autowired
    private UserAccountMapper userAccountMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Value("${secret.user-password}")
    private String bt;
    @Autowired
    MailUtil mailUtil;


    /**
     * @description 验证用户邮箱
     * @param email
     * @return
     */
    public WebResult checkUserEmail(String email) {
        //redis检查是否已经发过邮件了，避免重复发送
        Jedis jedis = RedisDS.create().getJedis();
        String checkValidationCode = jedis.get(email);

        if(checkValidationCode!=null){
            return WebResult.failWebResult(2002);
        }
        //生成邮件内容并发送
        MailBean mailBean = new MailBean();
        String validationCode = mailUtil.generateVerificationCode(6);
        String content = "请您在3分钟内完成邮箱验证，请勿将该验证码转发给他人:" + validationCode;
        mailBean.setRecipient(email).setSubject("灵犀：邮箱验证").setContent(content);
        //注意：封装了异步发送
        mailUtil.sendSimpleEmail(mailBean);

        //redis定时保存email和验证码
        SetParams setParams = new SetParams();
        setParams.ex(180);
        jedis.set(email,validationCode,setParams);
        jedis.close();

        return WebResult.okWebResult();
    }

    /**
     * @description 用户注册
     * @param userSign
     * @return
     */
    @Transactional(rollbackFor = {Exception.class})
    public WebResult userSign(UserSignDTO userSign) throws Exception {
        UserAccountEntity user = userSign.getUserAccountEntity();
        //查看验证码是否正确
        Jedis jedis = RedisDS.create().getJedis();
        String realCode = jedis.get(user.getEmail());
        jedis.close();
        //验证码失效
        if(realCode==null){
            return WebResult.failWebResult(2001);
        }
        //验证码错误
        if(!realCode.equals(userSign.getVerificationCode())){
            return WebResult.failWebResult(2000);
        }
        //查询用户是否注册
        QueryWrapper<UserAccountEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("email",user.getEmail());
        Long count = userAccountMapper.selectCount(wrapper);
        //已经注册
        if(count !=0){
            return WebResult.failWebResult(1001);
        }
        //未注册：对密码进行加密，注册
        AESUtil aesUtil = new AESUtil(bt);
        userSign.getUserAccountEntity().setPassword(aesUtil.encode(user.getPassword()));
        userAccountMapper.insert(user);
        int userId =user.getUserId();
        UserInfoEntity userInfoEntity = new UserInfoEntity(userId);
        userInfoMapper.insert(userInfoEntity);
        return WebResult.okWebResult();
    }

    /**
     * @description 用户登录
     * @param user
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor = {Exception.class})
    public WebResult userLogin(UserAccountEntity user) throws Exception {
        //查询账户是否注册
        QueryWrapper<UserAccountEntity> userAccountWrapper = new QueryWrapper<>();
        userAccountWrapper.eq("email",user.getEmail());
        UserAccountEntity tempUser = userAccountMapper.selectOne(userAccountWrapper);
        //未注册
        if(tempUser ==null) {
            return WebResult.failWebResult(1000);
        }
        //已注册：核对密码是否正确
        AESUtil aesUtil = new AESUtil(bt);
        user.setPassword(aesUtil.encode(user.getPassword()));
        //System.out.println(user.getPassword());
        //密码正确：可以登录
        if(user.getPassword().equals(tempUser.getPassword())){
            //记录登录状态
            StpUtil.login(tempUser.getUserId());
            //处理返回给用户的数据
            StpUtil.getTokenValueByLoginId(tempUser.getUserId());
            String token = StpUtil.getTokenValueByLoginId(tempUser.getUserId());
            QueryWrapper<UserInfoEntity> userInfoWrapper = new QueryWrapper<>();
            userInfoWrapper.eq("user_id",tempUser.getUserId());
            UserInfoEntity userInfoEntity  = userInfoMapper.selectOne(userInfoWrapper);
            UserLoginVO userLoginVO = new UserLoginVO(token,userInfoEntity);
            return WebResult.okWebResult(userLoginVO);
        }
        //密码错误：返回密码错误的信息
        return WebResult.failWebResult(1003);
    }


}
